from wormbane.engine.ai import Ai
from wormbane.engine.create_game import load_or_create_game
from wormbane.ui.commands.commands import handle_command
from wormbane.ui.ui import Ui

import os, curses, signal


def main():
    def interrupt_handler(signal, frame):
        pass
    signal.signal(signal.SIGINT, interrupt_handler)
    os.chdir(os.environ['WORMBANEDIR'])
    game = load_or_create_game()
    ai = Ai()
    curses.wrapper(wrapped_main, game, ai)
    if game.quit_message is not None:
        print game.quit_message

def wrapped_main(stdscr, game, ai):
    ui = Ui(stdscr)
    while not game.quit:
        ui.update(game)
        command = ui.read_command()
        del game.messages[:]
        handle_command(command, game, ui)
        if game.hero_moved:
            game.turn += 1
            if game.hero.hallucinating and game.hero.hallucinating < game.turn:
                game.hero.hallucinating = 0
                game.write(game.hero, 'snaps back to reality')
            ai.update(game)
            game.hero_moved = False


if __name__ == '__main__':
    main()
